#include "WebPage.h"
#include <sstream>
#include"tinyxml2.h"

using std::ostringstream;
using namespace tinyxml2;

WebPage::WebPage(const int docid, const string &title, const string &url, const string &content)
    : _docid(docid), _docTitle(title), _docUrl(url), _docConten(content)
{
    putDoc();
}

WebPage::WebPage(const string &article)
    : _doc(article)
{
    init();
}

void WebPage::putDoc()
{
    ostringstream oss(_doc);
    oss << "<doc>\n\t<docid>" << _docid << "</docid>\n\t<title>" << _docTitle << "</title>\n\t<link>" << _docUrl << "</link>\n\t<content>" << _docConten << "</content>\n</doc>\n";
}

void WebPage::init()
{
    XMLDocument doc;
    XMLError ret =doc.Parse(_doc.c_str());
    XMLElement* itemNode=doc.FirstChildElement("doc");
    _docid=std::stoi(itemNode->FirstChildElement("docid")->GetText());
    string _docTitle= itemNode->FirstChildElement("title")->GetText();
    string _docUrl = itemNode->FirstChildElement("link")->GetText();
    string _docConten = itemNode->FirstChildElement("content")->GetText();
}

// 获取文章号码
int WebPage::getDocid()
{
    return _docid;
}

// 获取整个文章

string WebPage::getDoc()
{
    return _doc;
}

 ostream& operator<<( ostream& os ,const WebPage& rhs)
 {
    os<<rhs._doc;
    return os;
 }
     void to_json(nlohmann::json& j,const WebPage& we)
    {
        j=nlohmann::json{{"doc",we._doc},
                         {"id",we._docid},
                         {"title",we._docTitle},
                         {"url",we._docUrl},
                         {"content",we._docConten}};
    }
     void from_json(const nlohmann::json & j , WebPage& we)
     {
        j.at("doc").get_to(we._doc);
        j.at("id").get_to(we._docid);
        j.at("title").get_to(we._docTitle);
        j.at("url").get_to(we._docUrl);
        j.at("content").get_to(we._docConten);

     }